﻿using System;
using System.Composition;
using System.Diagnostics;
using System.Windows.Input;
using Unread.App.Common;
using Unread.App.Services.Interfaces;
using Unread.App.Views;
using Unread.Business.Services.Interfaces;

namespace Unread.App.ViewModels
{
    [Export]
    public class AddFeedViewModel : BindableBase
    {
        private readonly IFeedAdder _feedAdder;
        private readonly INavigationService _navigationService;

        private string _url;
        public string Url
        {
            get { return _url; }
            set { SetProperty(ref _url, value); }
        }

        private bool _isLoading;
        public bool IsLoading
        {
            get { return _isLoading; }
            set { SetProperty(ref _isLoading, value); }
        }

        private string _errorMessage;
        public string ErrorMessage
        {
            get { return _errorMessage; }
            set { SetProperty(ref _errorMessage, value); }
        }

        [ImportingConstructor]
        public AddFeedViewModel(IFeedAdder feedAdder, INavigationService navigationService)
        {
            if (feedAdder == null) throw new ArgumentNullException("feedAdder");
            if (navigationService == null) throw new ArgumentNullException("navigationService");

            _feedAdder = feedAdder;
            _navigationService = navigationService;

            AddFeedCommand = new DelegateCommand(AddFeed, CanAddFeed);
            HomeCommand = new DelegateCommand(GoHome);
        }

        #region AddFeedCommand

        public ICommand AddFeedCommand { get; private set; }

        private bool CanAddFeed(object arg)
        {
            if (IsLoading)
                return false;

            if (arg == null)
                return false;

            return UrlValidator.IsValid(arg.ToString());
        }

        private async void AddFeed(object obj)
        {
            IsLoading = true;

            try
            {
                await _feedAdder.Add(new Uri(obj.ToString()));
                _navigationService.Navigate(typeof(UnreadPage));
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex);
                ErrorMessage = ex.Message;
            }
            finally
            {
                IsLoading = false;
            }
        }

        #endregion

        #region HomeCommand

        public ICommand HomeCommand { get; set; }

        private void GoHome(object obj)
        {
            _navigationService.Navigate(typeof(UnreadPage));
        }

        #endregion
    }
}
